package org.darkforest.merchant.controller;

import com.aliyun.oss.OSSClient;
import org.darkforest.common.logger.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import java.util.LinkedList;

/**
 * Created by chenyu on 15/1/29.
 * 使用阿里云oss管理图片视频的控制类
 */
@RequestMapping(value = "/oss")
@Controller
public class AliOssController {

    @RequestMapping(value = "demo", method = RequestMethod.GET)
    public String ossdemo() {
        return "album/ossdemo";
    }

    @RequestMapping(value = "")
    public String uploadFile() {

        return "";
    }

    LinkedList<FileMeta> files = new LinkedList<FileMeta>();
    FileMeta fileMeta = null;

    /**
     * ************************************************
     * URL: /oss/upload
     * upload(): receives files
     *
     * @param request  : MultipartHttpServletRequest auto passed
     * @return LinkedList<FileMeta> as json format
     * **************************************************
     */
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public
    @ResponseBody
    LinkedList<FileMeta> upload(MultipartHttpServletRequest request) {

        //1. build an iterator
        Iterator<String> itr = request.getFileNames();
        MultipartFile mpf;

        //2. get each file
        while (itr.hasNext()) {
            //2.1 get next MultipartFile
            mpf = request.getFile(itr.next());
            System.out.println(mpf.getOriginalFilename() + " uploaded! " + files.size());

            //2.2 if files > 10 remove the first from the list
            if (files.size() >= 10)
                files.pop();

            //2.3 create new fileMeta
            fileMeta = new FileMeta();
            fileMeta.setFileName(mpf.getOriginalFilename());
            fileMeta.setFileSize(mpf.getSize() / 1024 + " Kb");
            fileMeta.setFileType(mpf.getContentType());

            try {
                fileMeta.setBytes(mpf.getBytes());

                // copy file to local disk (make sure the path "e.g. D:/temp/files" exists)
                FileCopyUtils.copy(mpf.getBytes(), new FileOutputStream("/Users/valentina/Documents/temp/" + mpf.getOriginalFilename()));
                File uploadFile = new File("/Users/valentina/Documents/temp/" + mpf.getOriginalFilename());
                //上传到云空间
                String ACCESS_ID = "OmNrbdLLay3dRWq0";
                String ACCESS_KEY = "clisGnrj38soYlQb2BZ9PPIHnvxNdU";
                String endPoint = "http://oss-cn-beijing.aliyuncs.com/";
                String bucketName = "bwmall-develop";
                // 使用默认的OSS服务器地址创建OSSClient对象。
                OSSClient client = new OSSClient(endPoint, ACCESS_ID, ACCESS_KEY);
//                ossUploadFile(client, bucketName, "test", uploadFile);
            } catch (IOException e) {
                Logger.error(AliOssController.class, "Exception while upload file to oss, {}", e);
            }
            //2.4 add to files
            files.add(fileMeta);
        }
        // result will be like this
        // [{"fileName":"app_engine-85x77.png","fileSize":"8 Kb","fileType":"image/png"},...]
        return files;
    }

    /**
     * ************************************************
     * URL: /oss/get/{value}
     * get(): get file as an attachment
     *
     * @param response : passed by the server
     * @param value    : value from the URL
     * @return void
     * **************************************************
     */
    @RequestMapping(value = "/get/{value}", method = RequestMethod.GET)
    public void get(HttpServletResponse response, @PathVariable String value) {
        FileMeta getFile = files.get(Integer.parseInt(value));
        try {
            response.setContentType(getFile.getFileType());
            response.setHeader("Content-disposition", "attachment; filename=\"" + getFile.getFileName() + "\"");
            FileCopyUtils.copy(getFile.getBytes(), response.getOutputStream());
        } catch (IOException e) {
            Logger.error(AliOssController.class, "Exception while get file from oss, {}", e);
        }
    }


    class FileMeta {
        private String fileName;
        private String fileType;
        private String fileSize;

        private byte[] bytes;

        public String getFileName() {
            return fileName;
        }

        public void setFileName(String fileName) {
            this.fileName = fileName;
        }

        public String getFileType() {
            return fileType;
        }

        public void setFileType(String fileType) {
            this.fileType = fileType;
        }

        public String getFileSize() {
            return fileSize;
        }

        public void setFileSize(String fileSize) {
            this.fileSize = fileSize;
        }

        public byte[] getBytes() {
            return bytes;
        }

        public void setBytes(byte[] bytes) {
            this.bytes = bytes;
        }
    }

}
